import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

/**
 * @author meiqin liu（叶子）
 * @version 1.0.0
 * @date 2025/4/22 8:19
 */
//抢占式优先级调度
public class Scheduler {
    public PriorityQueue<PCB> readyQueue = new PriorityQueue<>(
            Comparator.comparingInt(p->p.priority)
    );
    public List<PCB> finished = new ArrayList<>();
    public List<PCB> suspended = new ArrayList<>();
    public PCB running = null;

    public void addProcess(PCB pcb) {
        if(MemoryManager.allocate(pcb)){
            readyQueue.offer(pcb);
        }else{
            suspended.add(pcb);//内存不足挂起
        }
    }
    public void step() {
        if(running != null){
            running.requireTime--;
            running.priority--;
            if(running.requireTime <= 0)
            {
                MemoryManager.free(running);
                running.status="完成";
                finished.add(running);
                running = null;
            }else{
                running.status = "就绪";
                readyQueue.offer(running);
                running = null;
            }
        }
        //从后备队列尝试调度挂起进程
        suspended.removeIf(pcb -> {
            if (MemoryManager.allocate(pcb)) {
                readyQueue.offer(pcb);
                return true;
            }
            return false;
        });

        if(!readyQueue.isEmpty()){
            running = readyQueue.poll();
            running.status = "运行中";
        }
    }
}
